import { fs, localPath } from './config'
import { clearSource } from './download'

/**
 * base64转ArrayBuffer
 * @param base64 base64图片
 */
const base64ToArrayBuffer = (base64: string) => {
  base64 = base64.replace(/^data:image\/\w+;base64,/, '')

  return uni.base64ToArrayBuffer(base64)
}

const regex = /^data:(.*?)(;base64)?,/

/**
 * base64转临时文件路径
 * @param base64 base64图片
 */
const base64ToFilePath = async (base64: string) => {
  const match = base64.match(regex)![1]
  const buffer = base64ToArrayBuffer(base64)
  let filePath = ''

  // #ifdef MP
  const typeList = match.split('/')
  const format = typeList[typeList.length - 1]

  filePath = `${localPath}/creation-${Date.now()}.${format}`

  try {
    if (!fs) throw '文件系统不可用'

    await new Promise((resolve, reject) => {
      fs!.writeFile({
        filePath,
        data: buffer,
        encoding: 'binary',
        success: resolve,
        fail: reject,
      })
    })
  } catch (err) {
    await clearSource()

    fs &&
      (await new Promise((resolve, reject) => {
        fs!.writeFile({
          filePath,
          data: buffer,
          encoding: 'binary',
          success: resolve,
          fail: reject,
        })
      }))
  }
  // #endif

  // #ifdef WEB
  filePath = URL.createObjectURL(new Blob([buffer], { type: match }))
  // #endif

  return filePath
}

export { base64ToArrayBuffer, base64ToFilePath }
